# -*- coding: utf-8 -*-

# 实现with连接服务器
import time

import paramiko
import select


class SSHClient:
    def __init__(self, hostname, port, username, password):
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password

    def __enter__(self):
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(
            hostname=self.hostname,
            port=self.port,
            username=self.username,
            password=self.password
        )
        return self

    def execute_command(self, command):
        print(f"execute command: {command}")
        stdin, stdout, stderr = self.client.exec_command(command)

        channels = [stdout.channel, stderr.channel]
        # 将内容实时打印出来
        while any(chan.closed is False for chan in channels):
            read_ready, _, _ = select.select(channels, [], [], 1.0)

            if stdout.channel in read_ready:
                while stdout.channel.recv_ready():
                    print(stdout.channel.recv(1024).decode(), end='')

            if stderr.channel in read_ready:
                while stderr.channel.recv_ready():
                    print(stderr.channel.recv(1024).decode(), end='')

        return "OK"

    def execute_commands_in_directory(self, commands):
        """
        Executes commands in a specified directory using invoke_shell.
        :param commands: list of commands to run in the directory
        """
        chdir_cmd = self.client.get_transport().open_session()
        chdir_cmd.invoke_shell()
        for command in commands:
            chdir_cmd.send(command)
            # output = chdir_cmd.recv(1024)
            # print(output.decode("utf-8"), end="\n")
        chdir_cmd.close()
        return "OK"

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.client:
            self.client.close()
